package com.biz.controller.sys;

/*************************************************************************
 * 文件名称 ：UserController                        
 * 描述说明 ：用户人员控制类
 * 
 * 创建信息 : create by 刘佳佳 on 2014-5-10
 * 修订信息 : modify by (person) on (date) for (reason)
 * 
 * 版权信息 : Copyright (c) 2014 扬州北斗科技有限公司 
 **************************************************************************/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.biz.model.Pmodel.sys.Pmenu;
import com.biz.model.Pmodel.sys.PsysRole;
import com.biz.model.Pmodel.sys.Puser;
import com.biz.model.common.MessageBox;
import com.biz.model.common.Pager;
import com.biz.model.common.SessionInfo;
import com.biz.service.HService.sys.MenuServiceI;
import com.biz.service.HService.user.UserServiceI;
import com.biz.utils.ConfigUtil;
import com.biz.utils.FileUtil;
import com.biz.utils.MD5Util;
import com.biz.utils.PagerPropertyUtils;
import com.biz.utils.StringUtil;
import com.biz.utils.URLConectionUtil;
import com.framework.controller.BaseController;
import com.framework.entity.Global;
import com.framework.util.MD5;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	@Resource(name = "userService")
	private UserServiceI userService;

	@Resource(name = "menuService")
	private MenuServiceI menuService;

	@InitBinder("puser")
	public void initBinderFormBean2(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("puser.");
	}

	/**
	 * 系统登录方法
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/login")
	public ModelAndView Login(Puser puser, HttpServletRequest request)
			throws Exception {
		SessionInfo sessionInfo = new SessionInfo();
		HttpSession session = request.getSession();
		mv.clear();
		// 加载人员
		List<Puser> ulist = userService.findByPwd(puser);

		if (ulist != null && ulist.size() > 0) {
			Puser user = ulist.get(0);
			if (user != null) {
				if (user.getLoginName().equals("admin")
						|| user.getLoginName().equals("itadmin")) {
					sessionInfo.setUser(user);
					session.setAttribute(Global.USER_NAME, user.getPersonName());
					// 加载菜单json数据
					List<Pmenu> pmenuList = menuService.findPmenu();
					String menujson = JSON.toJSONString(pmenuList);
					sessionInfo.setMenus(menujson);
					session.setAttribute("version", ConfigUtil.get("version")
							.toString());
					session.setAttribute(ConfigUtil.getSessionInfoName(),
							sessionInfo);
					mv.setViewName("/main/index");
				} else {
					mv.addObject("errorinfo", "只有管理员可以登录");
					mv.setViewName("main/error");
				}
			} else {
				mv.addObject("errorinfo", "账户名或密码错误");
				mv.setViewName("main/error");
			}
		} else {
			mv.addObject("errorinfo", "账户名或密码错误");
			mv.setViewName("main/error");
		}
		return mv;
	}

	/**
	 * 退出系统
	 * 
	 * @param response
	 */
	@RequestMapping("logout")
	public String logout(HttpServletResponse response) {
		return "redirect:/login/login.jsp";
	}

	@RequestMapping("checkpwd")
	public @ResponseBody
	boolean checkpwd(String pwds) throws Exception {
		String pwd = getLocalSessionInfo().getUser().getPwd();
		pwds = MD5Util.md5(pwds);
		if (pwd.equals(pwds)) {
			return true;
		}
		return false;
	}

	/**
	 * 显示账号信息
	 * 
	 * @param response
	 * @param dtGridPager
	 * @throws Exception
	 */
	@RequestMapping("showUserGrid")
	public void showUserGrid(HttpServletResponse response, String dtGridPager)
			throws Exception {
		Pager pager = PagerPropertyUtils.copy(JSONObject
				.fromObject(dtGridPager));
		Map<String, Object> map = new HashMap<String, Object>();
		map = pager.getParameters();
		Map<String, Object> map2 = new HashMap<String, Object>();
		try {
			map.put("loginName", pager.getParameters().get("loginName")
					.toString().trim());
		} catch (Exception e) {
		}
		try {
			map.put("personName", pager.getParameters().get("personName")
					.toString().trim());
		} catch (Exception e) {
		}
		try {
			map.put("phone", pager.getParameters().get("phone").toString()
					.trim());
		} catch (Exception e) {
		}
		try {
			map.put("startDate", pager.getParameters().get("startDate")
					.toString().trim());
		} catch (Exception e) {
		}
		try {
			map.put("endDate", pager.getParameters().get("endDate").toString()
					.trim());
		} catch (Exception e) {
		}
		try {
			map.put("minMoney", pager.getParameters().get("minMoney")
					.toString().trim());
		} catch (Exception e) {
		}
		try {
			map.put("maxMoney", pager.getParameters().get("maxMoney")
					.toString().trim());
		} catch (Exception e) {
		}
		try {
			map.put("minIntegral", pager.getParameters().get("minIntegral")
					.toString().trim());
		} catch (Exception e) {
		}
		try {
			map.put("maxIntegral", pager.getParameters().get("maxIntegral")
					.toString().trim());
		} catch (Exception e) {
		}
		pager.setParameters(map);
		Pager<Puser> list = userService.findByType(pager);
		writeJson(list, response);
	}

	/**
	 * 显示角色
	 * 
	 * @param response
	 * @param dtGridPager
	 * @throws Exception
	 */
	@RequestMapping("showRole")
	public void showRole(HttpServletResponse response) throws Exception {
		List<PsysRole> list = userService.findRole();
		writeJson(list, response);
	}

	/**
	 * 新增用户方法
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/addUser")
	public @ResponseBody
	MessageBox addUser(Puser puser, HttpServletResponse response)
			throws Exception {
		MessageBox box = new MessageBox();
		try {
			boolean flag = userService.findbyLoginName(puser.getLoginName());
			if (flag) {
				box.setMsg("保存失败，登陆名称不能重复！");
				box.setSuccess(false);
			} else {
				userService.saveUser(puser, getLocalSessionInfo().getUser());
			}
		} catch (Exception e) {
			box.setMsg("保存失败");
			box.setSuccess(false);
			logger.error("", e);
		}
		return box;
	}

	/**
	 * 编辑账号
	 * 
	 * @param id
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("toEdit")
	public void toEdit(String id, HttpServletResponse response)
			throws Exception {
		Puser user = userService.getinfoById(id);
		writeJson(user, response);

	}

	/**
	 * 修改账号信息
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateUser")
	public @ResponseBody
	MessageBox updateUser(HttpServletResponse response, Puser puser)
			throws Exception {
		MessageBox box = new MessageBox();
		try {
			if (puser != null) {

				boolean flag = userService.updateUser(puser,
						getLocalSessionInfo().getUser());
				if (flag) {
					box.setMsg("保存失败！");
					box.setSuccess(false);
				}
			}
		} catch (BeansException e) {
			box.setMsg("修改失败");
			box.setSuccess(false);
			logger.error("", e);
		}
		return box;
	}

	/**
	 * 批量删除账号
	 */
	@RequestMapping(value = "/remove")
	public @ResponseBody
	MessageBox remove(HttpServletResponse response, String ids) {
		try {
			int i = userService.deleteByIds(ids, getLocalSessionInfo()
					.getUser());
			if (i == 0) {
				box.setMsg("删除成功");
			} else {
				box.setMsg("删除失败,异常错误或者没有这个账号");
			}
		} catch (Exception e) {
			box.setMsg("删除失败");
			box.setSuccess(false);
			logger.error("", e);
		}
		return box;
	}

	/**
	 * 修改密码
	 * 
	 * @param response
	 * @param pwd
	 * @throws Exception
	 */
	@RequestMapping("doChangePwd")
	public void doChangePwd(HttpServletResponse response, String oldpwd,
			String newpwd) throws Exception {
		String msg = "";
		Puser puser = getLocalSessionInfo().getUser();
		oldpwd = MD5.md5(oldpwd);
		// newpwd=MD5.md5(newpwd);
		if (!oldpwd.equals(puser.getPwd())) {
			msg = "wrongpwd";
		} else {
			try {
				puser.setPwd(newpwd);
				// userService.updatePwdForChange(puser);
				// String url =
				// "http://localhost:8080/bsi/userInterface/editUserMall.action";
				String url = ConfigUtil.get("uap2");
				Map<String, String> map = new HashMap<String, String>();
				map.put("userJSON", JSON.toJSONString(puser));
				String x = URLConectionUtil.httpURLConnectionPostDiy(url, map);
				x = URLDecoder.decode(x, "utf-8");
				Map<String, String> map1 = JSON.parseObject(x, Map.class);
				if (map1.get("flag").equals("fail")) {
					msg = "fail";
				} else {
					msg = "success";
				}
			} catch (Exception e) {
				msg = "fail";
			}

		}
		writeJson(msg, response);
	}

	/**
	 * 添加活动菜单
	 */
	@RequestMapping(value = "/addActivityMenu")
	public void addActivityMenu(HttpServletResponse response, String id) {
		SessionInfo sessionInfo = getLocalSessionInfo();
		sessionInfo.setActivityMenuId(id);

		writeJson(box, response);
	}

	/**
	 * 导出账号信息
	 * 
	 * @param response
	 * @param puser
	 * @param outputStream
	 * @throws Exception
	 */
	@RequestMapping("exportExcel")
	public void exportExcel(HttpServletResponse response,
			ServletOutputStream outputStream, String parameters)
			throws Exception {
		JSONObject jsonobject = JSONObject.fromObject(parameters);
		Map<String, Object> map = new HashMap<String, Object>();
		if (!StringUtil.isNullOrEmpty(jsonobject.get("loginName"))) {
			map.put("loginName", jsonobject.get("loginName").toString());
		} else if (!StringUtil.isNullOrEmpty(jsonobject.get("personName"))) {
			map.put("personName", jsonobject.get("personName").toString());
		} else if (!StringUtil.isNullOrEmpty(jsonobject.get("startDate"))) {
			map.put("startDate", jsonobject.get("startDate").toString());
		} else if (!StringUtil.isNullOrEmpty(jsonobject.get("phone"))) {
			map.put("phone", jsonobject.get("phone").toString());
		} else if (!StringUtil.isNullOrEmpty(jsonobject.get("endDate"))) {
			map.put("endDate", jsonobject.get("endDate").toString());
		} else if (!StringUtil.isNullOrEmpty(jsonobject.get("minMoney"))) {
			map.put("minMoney", jsonobject.get("minMoney").toString());
		} else if (!StringUtil.isNullOrEmpty(jsonobject.get("maxMoney"))) {
			map.put("maxMoney", jsonobject.get("maxMoney").toString());
		} else if (!StringUtil.isNullOrEmpty(jsonobject.get("minIntegral"))) {
			map.put("minIntegral", jsonobject.get("minIntegral").toString());
		} else if (!StringUtil.isNullOrEmpty(jsonobject.get("maxIntegral"))) {
			map.put("maxIntegral", jsonobject.get("maxIntegral").toString());
		}
		List<Puser> list = userService.findExportExcel(map);
		String[] fstring = { "账号", "类型", "账户余额", "积分", "优惠券", "真实姓名", "联系电话",
				"创建时间" };
		setExcelStyle(list, response, outputStream, fstring);
	}

	/**
	 * 设置导出excel样式
	 * 
	 * @param list
	 * @throws Exception
	 */
	public void setExcelStyle(List<Puser> list, HttpServletResponse response,
			ServletOutputStream outputStream, String[] fstring)
			throws Exception {
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("sheet1");
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow(0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

		if (fstring.length > 0) {
			for (int k = 0; k < fstring.length; k++) {
				HSSFCell cell = row.createCell(k);
				cell.setCellValue(fstring[k]);
				cell.setCellStyle(style);
			}
		}

		// 第五步，写入实体数据
		for (int i = 0; i < list.size(); i++) {
			DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			row = sheet.createRow(i + 1);
			Puser user = list.get(i);
			// 第四步，创建单元格，并设置值
			String type = "";
			String createTime = "";
			/*
			 * if(user.getType()!=null){ int intType=user.getType(); }else{
			 * user.setType(type); }
			 */
			int intType = 1;
			createTime = sdf.format(user.getCreateTime());
			// 根据type值显示对应类型
			if (intType == 1) {
				type = "微信用户";
			} else if (intType == 2) {
				type = "等级2";
			} else if (intType == 3) {
				type = "等级3";
			} else if (intType == 4) {
				type = "等级4";
			} else if (intType == 5) {
				type = "等级5";
			} else if (intType == 6) {
				type = "等级6";
			}

			row.createCell(0).setCellValue(user.getLoginName());
			row.createCell(1).setCellValue(type);
			row.createCell(2).setCellValue(user.getMoney());
			row.createCell(3).setCellValue(user.getIntegral());
			row.createCell(4).setCellValue(user.getCoupons());
			row.createCell(5).setCellValue(user.getPersonName());
			row.createCell(6).setCellValue(user.getPhone());
			row.createCell(7).setCellValue(createTime);
		}
		// 第六步，将文件存到指定位置
		try {
			File file = new File("E:/file/downLoad");
			if (!file.exists()) {
				file.mkdir();
			}
			String serverPath = ConfigUtil.get("downLoad");
			String randomfile = FileUtil.getListNum(FileUtil
					.getRandomString2(5));
			serverPath = serverPath + "/" + randomfile + ".xls";
			FileOutputStream fout = new FileOutputStream(serverPath);
			wb.write(fout);
			fout.close();
			download(serverPath, response);
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	/**
	 * 下载excel
	 * 
	 * @param path
	 * @param response
	 */
	private void download(String path, HttpServletResponse response) {
		try {

			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// response.setContentType("application/x-excel");
			response.setContentType("application/binary;charset=utf-8");
			response.setHeader("Content-disposition", "attachment; filename="
					+ filename);// 组装附件名称和格式
			int len = 0;
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			OutputStream out = new BufferedOutputStream(
					response.getOutputStream());
			byte[] buffer = new byte[5120];
			while ((len = fis.read(buffer)) > 0) // 切忌这后面不能加 分号 ”;“
			{
				out.write(buffer, 0, len);// 向客户端输出，实际是把数据存放在response中，然后web服务器再去response中读取
			}
			fis.close();
			out.flush();
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 加载等级
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("LoadLevel")
	public @ResponseBody
	List<Map<String, Object>> LoadLevel() throws Exception {
		List<Map<String, Object>> list = userService.LoadLevel();
		return list;
	}

}